package com.azt.back.action.product;

import com.alibaba.fastjson.JSON;
import com.azt.api.enums.ProStockOperateType;
import com.azt.api.enums.ProStockType;
import com.azt.api.enums.ProductStateEnum;
import com.azt.api.pojo.Brand;
import com.azt.api.pojo.ProSku;
import com.azt.api.pojo.Product;
import com.azt.api.pojo.ProductStock;
import com.azt.api.service.*;
import com.azt.back.action.BaseAction;
import com.azt.back.util.ContextUtils;
import com.azt.back.util.Globals;
import com.azt.model.AjaxJson;
import com.azt.model.Ret;
import com.azt.model.page.Pagination;
import com.azt.utils.CommonUtil;
import com.azt.utils.RequestUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xiaoleilu.hutool.convert.Convert;
import com.xiaoleilu.hutool.util.ArrayUtil;
import com.xiaoleilu.hutool.util.CollectionUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 *                    _ooOoo_
 *                   o8888888o
 *                   88" . "88
 *                   (| -_- |)
 *                    O\ = /O
 *                ____/`---'\____
 *              .   ' \\| |// `.
 *               / \\||| : |||// \
 *             / _||||| -:- |||||- \
 *               | | \\\ - /// | |
 *             | \_| ''\---/'' | |
 *              \ .-\__ `-` ___/-. /
 *           ___`. .' /--.--\ `. . __
 *        ."" '< `.___\_<|>_/___.' >'"".
 *       | | : `- \`.;`\ _ /`;.`/ - ` : | |
 *         \ \ `-. \_ __\ /__ _/ .-` / /
 * ======`-.____`-.___\_____/___.-`____.-'======
 *                    `=---='
 *
 * .............................................
 *          佛祖保佑             永无BUG
 */
@Controller
@RequestMapping("/product")
public class ProductAction extends BaseAction {

    @Autowired
    private ProductService productService;

    @Autowired
    private ProCategoryService categoryService;

    @Autowired
    private ProCategoryBrandService categoryBrandService;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private IntegralService integralService;

    @Autowired
    private DictionaryService dictService;

    @Autowired
    private ConfigService configService;

    @Autowired
    private MsgConfigService msgConfigService;

    @RequestMapping("/listProduct.do")
    public String listProduct(Model model) {
        int pageNo = getParaToInt("pageNo", 1);
        Map param = CommonUtil.getParameterMap(request);
        Integer tab = getParaToInt("tab", 1);
        tab = tab == null ? 1 : tab;

        Integer companyId = getParaToInt("companyId");
        if(companyId != null) {
            tab = 1;
            model.addAttribute("company", companyService.getCompanyById(companyId));
        }
        Date sdate = getParaToDate("sdate");
        Date edate = getParaToDate("edate");
        if(sdate != null) {
            param.put("pubSdate", sdate);
        }
        if(edate != null) {
            param.put("pubEdate", DateUtils.addDays(edate, 1));
        }

        Integer ifPub = 1;
        String state = "1";
        switch (tab) {
            case 2:
                //待审核
                state = "0,3";
                break;
            case 3:
                //已下架
                ifPub = 0;
                break;
            case 4:
                //未通过审核
                state = "2";
        }
        param.put("ifPub", ifPub);
        param.put("state", state);
        param.put("tab", tab);

        Page page = PageHelper.startPage(pageNo, Globals.PAGE_SIZE);
        List<Map> list = productService.searchMgrProduct(param);

        Pagination pagination = new Pagination(page, list);
        pagination.setList(list);
        pagination.setParams(param);

        model.addAttribute("pagination", pagination);
        model.addAttribute("WEB_SITE", configService.getConfigValueByCode("WEB_SITE"));
        model.addAttribute("skuCount", productService.getMgrProductSkuCount(param));
        param.remove("pubSdate");
        param.remove("pubEdate");
        RequestUtils.MapToModelMap(param, request);
        return "product/listProduct";
    }

    @ResponseBody
    @RequestMapping("/listSku.do")
    public AjaxJson listSku() {
        Integer productId = getParaToInt("productId");
        if(productId != null) {
            List<ProSku> list = productService.findProSkuByProId(productId);
            return AjaxJson.success().setObj(list);
        } else {
            return AjaxJson.error();
        }
    }

    @RequestMapping(value = "/editProduct.do", method = RequestMethod.GET)
    public String loadEditProduct(Model model) {
        Integer productId = getParaToInt("productId");      //更新的商品id

        if(productId != null) {
            //更新商品
            Product product = productService.getProductById(productId);

            model.addAttribute("product", product);

            //分类
            Map cates = categoryService.getParentCates(product.getCategoryTId());
            //所属品牌
            List<Brand> brandList = categoryBrandService.findBrandByCategoryId(1, null, null, null, product.getCategoryTId());

            List<ProSku> skuList = productService.findProSkuByProId(productId);

            model.addAttribute("cates", cates);
            model.addAttribute("brandList", brandList);
            model.addAttribute("unitList", dictService.getDictionByParentCode("PRO_UNIT"));     //单位
            model.addAttribute("skuList", skuList);
        }

        return "product/editProduct";
    }

    @ResponseBody
    @RequestMapping(value = "/editProduct.do", method = RequestMethod.POST)
    public AjaxJson editProduct() {
        Integer productId = getParaToInt("productId");
        String productName = getParaTrim("productName");
        String subName = getParaTrim("subName");
        Integer brandId = getParaToInt("brandId");
        String model = getParaTrim("model");
        String unit = getParaTrim("unit");
        String picPath = getParaTrim("picPath");
        String descr = getPara("descr");
        Integer serviceDuration = getParaToInt("serviceDuration");
        String serviceUnit = getPara("serviceUnit");
        String service = getPara("service");
        String attachfile = getPara("attachfile");
        String attachName = getPara("attachName");
        String _skuList = getPara("skuList");

        if(productId != null && !StrUtil.hasBlank(productName, picPath, descr, _skuList)) {
            List<Map> skuList = JSON.parseArray(_skuList, Map.class);
            if(CollectionUtil.isNotEmpty(skuList)) {
                Product product = productService.getProductById(productId);
                if (product != null) {
                    product.setName(productName);
                    product.setSubName(subName);
                    product.setBrandId(brandId);
                    product.setModel(model);
                    product.setUnit(unit);
                    product.setPicPath(picPath);
                    product.setDescr(descr);
                    product.setServiceDuration(serviceDuration);
                    product.setServiceUnit(serviceDuration != null ? serviceUnit : null);
                    product.setService(service);
                    product.setAttachfile(attachfile);
                    product.setAttachName(attachName);
                    productService.updateProduct(product);

                    for (Map m : skuList) {
                        Integer skuId = Convert.toInt(m.get("skuId"));
                        Double price = Convert.toDouble(m.get("price"));
                        Double memberPrice = Convert.toDouble(m.get("memberPrice"));
                        Integer changeStock = Convert.toInt(m.get("changeStock"));
                        if(changeStock.intValue() != 0) {
                            //库存
                            ProductStock productStock = new ProductStock();
                            productStock.setProductId(product.getId());
                            productStock.setSkuId(skuId);
                            productStock.setOperateid(ContextUtils.getAdmin().getId());
                            productStock.setType(changeStock > 0 ? ProStockType.IN.getValue() : ProStockType.OUT.getValue());
                            productStock.setQuantity(Math.abs(changeStock));
                            productStock.setOperateType(changeStock > 0 ? ProStockOperateType.IN.getValue() : ProStockOperateType.OUT.getValue());
                            productService.insertProductStockSelective(productStock);
                        }
                        //sku信息
                        ProSku proSku = productService.getProSkuById(skuId);
                        proSku.setPrice(price);
                        proSku.setMemberPrice(memberPrice);
                        productService.updateProSkuSelective(proSku);
                    }
                    return AjaxJson.success();
                }
            }
        }
        return AjaxJson.error();
    }

    @ResponseBody
    @RequestMapping(value = "/auditProduct.do", method = RequestMethod.POST)
    public AjaxJson auditProduct() {
        Integer productId = getParaToInt("productId");
        Boolean pass = getParaToBool("pass");
        String auditOpinion = getParaTrim("auditOpinion");

        if(productId != null && pass != null) {
            if(!pass && StrUtil.isBlank(auditOpinion)) {
                return AjaxJson.error("请输入驳回原因");
            }
            Product product = productService.getProductById(productId);
            if(product != null) {
                if(pass) {
                    product.setState(ProductStateEnum.YES.getValue());
                    if(product.getFirstPass() != null && product.getFirstPass().intValue() == 1) {
                        //第一次审核通过
                        //赠送积分
                        integralService.addUserRecord(product.getUserId(), null, null, "发布商品赠送积分", ContextUtils.getAdmin().getId());
                        product.setFirstPass(0);
                    }
                } else {
                    product.setAuditOpinion(auditOpinion);
                    product.setState(ProductStateEnum.NO.getValue());
                    msgConfigService.sendMessage("PRODUCT_NOPASS", Ret.create("productName", product.getName()).set("reason", auditOpinion), null, product.getUserId());
                }
                productService.updateProductSelective(product);
                return AjaxJson.success();
            }
        }
        return AjaxJson.error();
    }

    /**
     * 下架商品
     * */
    @ResponseBody
    @RequestMapping(value = "/downProduct.do", method = RequestMethod.POST)
    public AjaxJson downProduct() {
        Integer productId = getParaToInt("productId");

        if(productId != null) {
            Product product = productService.getProductById(productId);
            if(product != null && product.getIfPub().intValue() == 1) {
                product.setIfPub(0);
                productService.updateProductSelective(product);

                //扣积分
                integralService.addUserRecord(product.getUserId(), "product_offline", null, null, ContextUtils.getAdmin().getId());
                return AjaxJson.success();
            }
        }
        return AjaxJson.error();
    }

    /**
     * 上架商品
     * */
    @ResponseBody
    @RequestMapping(value = "/upProduct.do", method = RequestMethod.POST)
    public AjaxJson upProduct() {
        Integer productId = getParaToInt("productId");

        if(productId != null) {
            Product product = productService.getProductById(productId);
            if(product != null && product.getIfPub().intValue() == 0) {
                product.setIfPub(1);
                productService.updateProductSelective(product);
                return AjaxJson.success();
            }
        }
        return AjaxJson.error();
    }

    @ResponseBody
    @RequestMapping(value = "/updateCenPrice.do", method = RequestMethod.POST)
    public AjaxJson updateCenPrice() {
        String[] skuIdArray =  request.getParameterValues("skuId");
        String[] cenPriceArray = request.getParameterValues("cenPrice");

        if(ArrayUtil.isNotEmpty(skuIdArray) && ArrayUtil.isNotEmpty(cenPriceArray)) {
            for(int i = 0, len = skuIdArray.length; i < len; i++) {
                Integer skuId = Convert.toInt(skuIdArray[i]);
                Double cenPrice = Convert.toDouble(cenPriceArray[i]);
                if(skuId != null && cenPrice != null) {
                    productService.updateCenPrice(skuId, cenPrice);
                }
            }
            return AjaxJson.success();
        }
        return AjaxJson.error();
    }

    @ResponseBody
    @RequestMapping(value = "/updateHotPrice.do", method = RequestMethod.POST)
    public AjaxJson updateHotPrice() {
        String[] skuIdArray =  request.getParameterValues("skuId");
        String[] hotPriceArray = request.getParameterValues("hotPrice");

        if(ArrayUtil.isNotEmpty(skuIdArray) && ArrayUtil.isNotEmpty(hotPriceArray)) {
            for(int i = 0, len = skuIdArray.length; i < len; i++) {
                Integer skuId = Convert.toInt(skuIdArray[i]);
                Double hotPrice = Convert.toDouble(hotPriceArray[i]);
                if(skuId != null && hotPrice != null) {
                    productService.updateHotPrice(skuId, hotPrice);
                }
            }
            return AjaxJson.success();
        }
        return AjaxJson.error();
    }

}
